package com.vote.controller;

import com.vote.dto.BrandDto;
import com.vote.pojo.Brand;
import com.vote.pojo.BrandVo;
import com.vote.pojo.Page;
import com.vote.service.BrandService;
import com.vote.service.ImageService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017-08-04.
 */

@Controller
@RequestMapping("/brandManager")
public class BrandManagerController {
    private Logger log = Logger.getLogger(UserController.class);

    @Resource
    BrandService brandService;

    @Resource
    ImageService imageService;

    @RequestMapping("/getAllBrand")
    public String getAllBrand(HttpServletRequest request,Model model){
        log.info("查询所有品牌信息");
        List<Brand> brandList=brandService.getAllBrand();
        model.addAttribute("brandList",brandList);
        return "brandManager";
    }

    @RequestMapping("/getBrandByTypeLimit")

    public String getBrandByTypeLimit(HttpServletRequest request,Model model){
        log.info("根据品牌分类分页查询品牌信息");
        String brandType="教育";  //默认品牌分类
        int currentPage=1;    //默认当前页数
        int pageSize=2;        //默认每页记录数
        int total=brandService.getBrandCountByType(brandType);  //总记录数

        int pages=(total/pageSize==0? total/pageSize:total/pageSize+1);  //总页数


        Page page=new Page();
        page.setCurrentPage(pages);
        page.setPageSize(pageSize);
        page.setTotal(total);
        page.setPages(pages);
        page.setStartCount((page.getCurrentPage()-1)*pageSize);


        BrandVo brandVo=new BrandVo();
        brandVo.setPage(page);
        brandVo.setBrandType(brandType);

        //分页查询的品牌集合
        List<Brand> brandList=brandService.getBrandByTypeLimit(brandVo);

        //品牌logo的集合
        List<String> logoUrlList=new ArrayList<String>();
        for(Brand brand:brandList){
            logoUrlList.add(imageService.getImageUrl(brand.getBrandPhotoId()));
        }

        //包装品牌的集合
        List<BrandDto> brandDtoList=new ArrayList<BrandDto>();
        int orderCount=(page.getCurrentPage()-1)*pageSize+1;  //分页序号的起始序号

        for(int i=0;i<brandList.size();i++){
            Brand brand=brandList.get(i);
            BrandDto brandDto=new BrandDto();
            brandDto.setBrandId(brand.getBrandId());
            brandDto.setBrandName(brand.getBrandName());
            brandDto.setBrandVoteCount(brand.getBrandVoteCount());
            brandDto.setLogoUrl(logoUrlList.get(i));
            brandDto.setOrderId(orderCount+i);
            brandDtoList.add(brandDto);
        }

        model.addAttribute("brandDtoList",brandDtoList);
        model.addAttribute("page",page);
        return "brandManager";
    }
}
